﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace KitBuildingWF.Controls
{
    class TabControls
    {
        static TabControl mainTabControl = null;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mainTab">The tab control to be manipulated</param>
        public TabControls(TabControl mainTab)
        {
            mainTabControl = mainTab;
        }

        public static void HideTabPage(TabPage tp)
        {
            if (mainTabControl.TabPages.Contains(tp))
                mainTabControl.TabPages.Remove(tp);
        }


        private void ShowTabPage(TabPage tp)
        {
            ShowTabPage(tp, mainTabControl.TabPages.Count);
        }


        private void ShowTabPage(TabPage tp, int index)
        {
            if (mainTabControl.TabPages.Contains(tp)) return;
            InsertTabPage(tp, index);
        }


        private void InsertTabPage(TabPage tabpage, int index)
        {
            if (index < 0 || index > mainTabControl.TabCount)
                throw new ArgumentException("Index out of Range.");
            mainTabControl.TabPages.Add(tabpage);
            if (index < mainTabControl.TabCount - 1)
                do
                {
                    SwapTabPages(tabpage, (mainTabControl.TabPages[mainTabControl.TabPages.IndexOf(tabpage) - 1]));
                }
                while (mainTabControl.TabPages.IndexOf(tabpage) != index);
            mainTabControl.SelectedTab = tabpage;
        }


        private void SwapTabPages(TabPage tp1, TabPage tp2)
        {
            if (mainTabControl.TabPages.Contains(tp1) == false || mainTabControl.TabPages.Contains(tp2) == false)
                throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

            int Index1 = mainTabControl.TabPages.IndexOf(tp1);
            int Index2 = mainTabControl.TabPages.IndexOf(tp2);
            mainTabControl.TabPages[Index1] = tp2;
            mainTabControl.TabPages[Index2] = tp1;

            //Uncomment the following section to overcome bugs in the Compact Framework
            //tabControl1.SelectedIndex = tabControl1.SelectedIndex; 
            //string tp1Text, tp2Text;
            //tp1Text = tp1.Text;
            //tp2Text = tp2.Text;
            //tp1.Text=tp2Text;
            //tp2.Text=tp1Text;

        }
    }
}
